package com.group.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
 * 处理分页逻辑Tag
 * @author zst
 * @version 1.0
 */
public class PaginationTagHandler extends SimpleTagSupport {

    private int page;       // 当前页码
    private int pageCount;  // 总页数

    public void setPage(int page) {
        this.page = page;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    @Override
    public void doTag() throws JspException, IOException {
        getJspContext().getOut().write("<nav><ul class=\"pagination justify-content-center\">");

        // 上一页
        int prevPage = page - 1;
        getJspContext().getOut().write("<li class=\"page-item " + (page == 1 ? "disabled" : "") + "\">");
        getJspContext().getOut().write("<a class=\"page-link\" href=\"?page=" + prevPage + "\" tabindex=\"-1\" aria-disabled=\"" + (page == 1) + "\">上一页</a>");
        getJspContext().getOut().write("</li>");

        // 页码
        for (int pageNum = 1; pageNum <= pageCount; pageNum++) {
            boolean isActive = pageNum == page;
            getJspContext().getOut().write("<li class=\"page-item " + (isActive ? "active" : "") + "\">");
            getJspContext().getOut().write("<a class=\"page-link\" href=\"?page=" + pageNum + "\">" + pageNum + "</a>");
            getJspContext().getOut().write("</li>");
        }

        // 下一页
        int nextPage = page + 1;
        getJspContext().getOut().write("<li class=\"page-item " + (page == pageCount ? "disabled" : "") + "\">");
        getJspContext().getOut().write("<a class=\"page-link\" href=\"?page=" + nextPage + "\">下一页</a>");
        getJspContext().getOut().write("</li>");

        getJspContext().getOut().write("</ul></nav>");
    }
}
